package com.investigation.protect;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static android.content.Context.NOTIFICATION_SERVICE;

public class MyReceiver extends BroadcastReceiver {
    public boolean belongNow(int h){//所给时间是否属于现在的时区
        @SuppressLint("SimpleDateFormat") SimpleDateFormat now = new SimpleDateFormat("HH");
        int nowH=Integer.parseInt(now.format(new Date(System.currentTimeMillis())));
        return belong(nowH) == belong(h);
    }
    public int belong(int h){//所给时间属于哪个时区
        if(h>=10 && h<=22){
            if(h < 12){
                return 1;
            }else if(h < 14){
                return 2;
            }else if(h < 16){
                return 3;
            }else if(h < 18){
                return 4;
            }else if(h < 20){
                return 5;
            }else if(h < 22){
                return 6;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void showNotification(Context context) {
        NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        Intent hangIntent = new Intent();
        hangIntent.setComponent(new ComponentName("com.investigation", "com.investigation.MainActivity"));
        PendingIntent hangPendingIntent = PendingIntent.getActivity(context, 1001, hangIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new NotificationCompat.Builder(context, "investigation").setContentTitle("アンケートを取ってください").setContentText("クリックして記入します").setSmallIcon(R.mipmap.ic_launcher).setContentIntent(hangPendingIntent).setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher)).setAutoCancel(true).build();
        //响铃
        notification.defaults=Notification.DEFAULT_SOUND;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("investigation","アンケート通知", NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(notificationChannel);
        }
        manager.notify(520, notification);
    }
    public static void wakeUpAndUnlock(Context context){
        KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        kl.disableKeyguard();
        PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
        wl.acquire();
        wl.release();
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void handleJSON(String txt, Context context)  {
        Calendar cal=Calendar.getInstance();
        int realhour=cal.get(Calendar.HOUR_OF_DAY);
//        Toast.makeText(context,"当前小时"+String.valueOf(realhour),Toast.LENGTH_LONG).show();
        Log.i("emmmmm时间",String.valueOf(realhour));
        if (txt==null || txt.equals("")){
            if (realhour>=10 && realhour<22){
                showNotification(context);
            }else {
                Log.i("emmmmm没写且不在大事件内",String.valueOf(realhour));
            }
        }else{
            try{
                boolean haveAnswered=false;

                if (realhour>=10 && realhour<22){
                    JSONArray array= new JSONArray(txt);
                    for(int i=0;i<array.length();i++){
                        JSONObject job = array.getJSONObject(i);
                        @SuppressLint("SimpleDateFormat") SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
                        String y=ymd.format(new Date(Long.parseLong(job.getString("time")) * 1000L));
                        if(y.equals(ymd.format(new Date(System.currentTimeMillis())))){
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat h = new SimpleDateFormat("HH");
                            String hour=h.format(new Date(Long.parseLong(job.getString("time")) * 1000L));
                            if (belongNow(Integer.parseInt(hour))){
                                haveAnswered=true;
                            }
                        }
                    }
                }else {
                    Log.i("emmmmm","不在时间范围内");
                    haveAnswered=true;
                }
                if(haveAnswered){
                    Log.i("emmmmm","本时间段已完成,或不在本时间段,就不通知");
                }else {
                    Log.i("emmmmm","本时间段没完成，就通知");
                    showNotification(context);
                    wakeUpAndUnlock(context);
                }
            }catch (Exception ignored){
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
        TXTManager txtManager=new TXTManager();
        String txt=txtManager.read("config");
        Log.i("emmm","收到广播"+txt);
        handleJSON(txt,context);
        new Handler().postDelayed(new Runnable(){
            public void run() {
                Intent inten2t=new Intent();
                inten2t.setAction("广播2");
                inten2t.setComponent(new ComponentName(context.getPackageName(),context.getPackageName()+".MyReceiver"));
                context.sendBroadcast(inten2t);
            }
        }, 1000*10);
    }
}